<script lang="ts" setup>
import { ref, reactive, onMounted } from "vue";
import { getCategory } from "@/service/category";
import { h } from "vue";
import {
  Image,
  Message,
  Modal,
  type FormInstance,
  type TableColumnData,
  Button,
} from "@arco-design/web-vue";
import { storeToRefs } from "pinia";
import { useUserStore } from "@/store/user";
import Compressor from "compressorjs";
import type { Category } from "@/types/category";
import type { Good } from "@/types/good";
import { getGoods } from "@/service/good";

// 当前活动的模式: 'notice' 或 'banner'
const activeMode = ref("notice");

// =========== 通知配置相关 ===========
// 通知数据
const notices = ref<any[]>([]);
// 通知表格加载状态
const noticeLoading = ref(false);

// 通知表格列定义
const noticeColumns = <TableColumnData[]>[
  { title: "标题", dataIndex: "title", width: 140 },
  { title: "内容", dataIndex: "content" },
  { title: "创建时间", dataIndex: "createTime", width: 180 },
  {
    title: "操作",
    width: 160,
    render: (row: any) => {
      return h("div", [
        h(
          Button,
          {
            onClick: () => openNoticeModal("编辑", row.record),
          },
          () => "编辑"
        ),
        h(
          Button,
          {
            style: { marginLeft: "8px" },
            status: "danger",
            onClick: () => handleDeleteNotice(row.record.id),
          },
          () => "删除"
        ),
      ]);
    },
  },
];

// 获取通知数据
const fetchNotices = () => {
  noticeLoading.value = true;
  try {
    // 这里替换为实际的API调用
    // getNotices().then(res => {
    //   notices.value = res.data.list;
    // });

    // 模拟数据加载
    setTimeout(() => {
      noticeLoading.value = false;
    }, 500);
  } catch (e) {
    console.error("加载通知失败", e);
  } finally {
    noticeLoading.value = false;
  }
};

// 通知模态框表单
const noticeForm = reactive({
  id: undefined as number | undefined,
  title: "",
  content: "",
});

// 通知表单校验规则
const noticeRules = {
  title: [{ required: true, message: "请输入通知标题" }],
  content: [{ required: true, message: "请输入通知内容" }],
};

// 通知表单引用
const noticeFormRef = ref<FormInstance>();
// 通知模态框显示状态
const noticeModalVisible = ref(false);
// 通知模态框标题
const noticeModalTitle = ref("新增");

// 打开通知模态框
const openNoticeModal = (type: string, row?: any) => {
  noticeFormRef.value?.clearValidate();
  noticeFormRef.value?.resetFields();
  noticeForm.id = undefined;
  noticeForm.title = "";
  noticeForm.content = "";
  noticeModalTitle.value = type;

  if (type === "编辑" && row) {
    noticeForm.id = row.id;
    noticeForm.title = row.title;
    noticeForm.content = row.content;
  }

  noticeModalVisible.value = true;
};

// 处理通知模态框确认
const handleNoticeModalOk = () => {
  noticeFormRef.value?.validate().then((errors: any) => {
    if (errors) return;

    const isAdd = noticeModalTitle.value === "新增";
    // 如果是新增，并且已经有通知，则提示错误
    if (isAdd && notices.value.length > 0) {
      Message.error("最多只能有一条通知");
      return;
    }

    // 执行添加或更新操作
    // 替换为实际API调用
    if (isAdd) {
      // addNotice(noticeForm).then(res => {
      //   Message.success(res.message);
      //   fetchNotices();
      //   noticeModalVisible.value = false;
      // });
      notices.value = [
        {
          id: Date.now(),
          title: noticeForm.title,
          content: noticeForm.content,
          createTime: new Date().toLocaleString(),
        },
      ];
      Message.success("添加成功");
      noticeModalVisible.value = false;
    } else {
      // updateNotice(noticeForm).then(res => {
      //   Message.success(res.message);
      //   fetchNotices();
      //   noticeModalVisible.value = false;
      // });
      const index = notices.value.findIndex(
        (item) => item.id === noticeForm.id
      );
      if (index !== -1) {
        notices.value[index] = {
          ...notices.value[index],
          title: noticeForm.title,
          content: noticeForm.content,
        };
      }
      Message.success("更新成功");
      noticeModalVisible.value = false;
    }
  });
};

// 处理通知模态框取消
const handleNoticeModalCancel = () => {
  noticeModalVisible.value = false;
};

// 处理通知删除
const handleDeleteNotice = (id: number) => {
  Modal.confirm({
    title: "删除确认",
    content: "确定要删除此通知吗？",
    onOk: () => {
      // 调用删除通知的API
      // deleteNotice(id).then(res => {
      //   Message.success(res.message);
      //   fetchNotices();
      // });

      notices.value = notices.value.filter((item) => item.id !== id);
      Message.success("删除成功");
    },
  });
};

// =========== 首图配置相关 ===========
// 首图数据
const banners = ref<any[]>([]);
// 首图表格加载状态
const bannerLoading = ref(false);

// 首图表格列定义
const bannerColumns = <TableColumnData[]>[
  { title: "标题", dataIndex: "title", width: 140 },
  { title: "排序", dataIndex: "sort", width: 80 },
  {
    title: "图片",
    dataIndex: "img",
    render: (row: any) => {
      return h(Image, {
        width: 80,
        src: row.record.img ? "/api/file/" + row.record.img : "",
      });
    },
  },
  { title: "关联货品", dataIndex: "goodName" },
  { title: "创建时间", dataIndex: "createTime", width: 180 },
  {
    title: "操作",
    width: 160,
    render: (row: any) => {
      return h("div", [
        h(
          Button,
          {
            onClick: () => openBannerModal("编辑", row.record),
          },
          () => "编辑"
        ),
        h(
          Button,
          {
            style: { marginLeft: "8px" },
            status: "danger",
            onClick: () => handleDeleteBanner(row.record.id),
          },
          () => "删除"
        ),
      ]);
    },
  },
];

// 获取首图数据
const fetchBanners = () => {
  bannerLoading.value = true;
  try {
    // 替换为实际API调用
    // getBanners().then(res => {
    //   banners.value = res.data.list;
    // });

    setTimeout(() => {
      bannerLoading.value = false;
    }, 500);
  } catch (e) {
    console.error("加载首图失败", e);
  } finally {
    bannerLoading.value = false;
  }
};

// 首图表单
const bannerForm = reactive({
  id: undefined as number | undefined,
  title: "",
  sort: 0,
  img: "",
  goodId: undefined as number | undefined,
  goodName: "", // 用于显示已选货品名称
});

// 首图表单校验规则
const bannerRules = {
  title: [{ required: true, message: "请输入首图标题" }],
  img: [{ required: true, message: "请上传首图" }],
  goodId: [{ required: true, message: "请选择关联货品" }],
};

// 首图表单引用
const bannerFormRef = ref<FormInstance>();
// 首图模态框显示状态
const bannerModalVisible = ref(false);
// 首图模态框标题
const bannerModalTitle = ref("新增");
// 首图文件列表
const bannerFileList = ref<any[]>([]);

// 打开首图模态框
const openBannerModal = (type: string, row?: any) => {
  bannerFormRef.value?.clearValidate();
  bannerFormRef.value?.resetFields();
  bannerForm.id = undefined;
  bannerForm.title = "";
  bannerForm.sort = 0;
  bannerForm.img = "";
  bannerForm.goodId = undefined;
  bannerForm.goodName = "";
  bannerModalTitle.value = type;
  bannerFileList.value = [];

  if (type === "编辑" && row) {
    bannerForm.id = row.id;
    bannerForm.title = row.title;
    bannerForm.sort = row.sort;
    bannerForm.img = row.img;
    bannerForm.goodId = row.goodId;
    bannerForm.goodName = row.goodName || "";

    if (row.img) {
      bannerFileList.value = [
        {
          uid: row.id,
          name: row.img,
          status: "done",
          url: "/api/file/" + row.img,
        },
      ];
    }
  }

  bannerModalVisible.value = true;
};

// 处理首图模态框确认
const handleBannerModalOk = () => {
  bannerFormRef.value?.validate().then((errors: any) => {
    if (errors) return;

    const isAdd = bannerModalTitle.value === "新增";
    // 如果是新增，并且已经有3张首图，则提示错误
    if (isAdd && banners.value.length >= 3) {
      Message.error("最多只能有三张首图");
      return;
    }

    // 执行添加或更新操作
    // 替换为实际API调用
    if (isAdd) {
      // addBanner(bannerForm).then(res => {
      //   Message.success(res.message);
      //   fetchBanners();
      //   bannerModalVisible.value = false;
      // });
      banners.value.push({
        id: Date.now(),
        title: bannerForm.title,
        sort: bannerForm.sort,
        img: bannerForm.img,
        goodId: bannerForm.goodId,
        goodName: bannerForm.goodName,
        createTime: new Date().toLocaleString(),
      });
      Message.success("添加成功");
      bannerModalVisible.value = false;
    } else {
      // updateBanner(bannerForm).then(res => {
      //   Message.success(res.message);
      //   fetchBanners();
      //   bannerModalVisible.value = false;
      // });
      const index = banners.value.findIndex(
        (item) => item.id === bannerForm.id
      );
      if (index !== -1) {
        banners.value[index] = {
          ...banners.value[index],
          title: bannerForm.title,
          sort: bannerForm.sort,
          img: bannerForm.img,
          goodId: bannerForm.goodId,
          goodName: bannerForm.goodName,
        };
      }
      Message.success("更新成功");
      bannerModalVisible.value = false;
    }
  });
};

// 处理首图模态框取消
const handleBannerModalCancel = () => {
  bannerModalVisible.value = false;
};

// 处理首图删除
const handleDeleteBanner = (id: number) => {
  Modal.confirm({
    title: "删除确认",
    content: "确定要删除此首图吗？",
    onOk: () => {
      // 调用删除首图的API
      // deleteBanner(id).then(res => {
      //   Message.success(res.message);
      //   fetchBanners();
      // });

      banners.value = banners.value.filter((item) => item.id !== id);
      Message.success("删除成功");
    },
  });
};

// =========== 货品选择相关 ===========
// 货品选择模态框显示状态
const goodSelectModalVisible = ref(false);
// 货品搜索条件
const goodSearchFilters = reactive({
  name: "",
  type: "",
});
// 货品搜索结果
const searchGoods = ref<Good[]>([]);
// 货品加载状态
const goodSearchLoading = ref(false);
// 下拉类别列表
const categories = ref<Category[]>([]);

// 获取类别选项
const fetchCategories = () => {
  try {
    getCategory({ page: 1, pageSize: 100 }).then((res) => {
      categories.value = res.data.list;
    });
  } catch (e) {
    console.error("加载类别失败", e);
  }
};

// 搜索货品
const searchGoodsList = () => {
  goodSearchLoading.value = true;
  try {
    getGoods({
      ...goodSearchFilters,
      page: 1,
      pageSize: 10,
    }).then((res) => {
      searchGoods.value = res.data.list;
      goodSearchLoading.value = false;
    });
  } catch (e) {
    console.error("搜索货品失败", e);
    goodSearchLoading.value = false;
  }
};

// 选择货品
const selectGood = (good: Good) => {
  bannerForm.goodId = good.id;
  bannerForm.goodName = good.name;
  goodSelectModalVisible.value = false;
};

// 打开货品选择模态框
const openGoodSelectModal = () => {
  goodSearchFilters.name = "";
  goodSearchFilters.type = "";
  searchGoods.value = [];
  goodSelectModalVisible.value = true;
};

// 用户信息
const { userCredit } = storeToRefs(useUserStore());

// 图片上传前处理
const onBeforeUpload = (file: File): Promise<File> => {
  return new Promise<File>((resolve, reject) => {
    const isLt2M = file.size / 1024 / 1024 < 2;
    if (!isLt2M) {
      Message.error("图片必须小于2MB!");
      reject(false);
      return;
    }
    new Compressor(file, {
      quality: 0.8, // 压缩质量
      maxWidth: 1200, // 最大宽度
      maxHeight: 1200, // 最大高度
      success(result) {
        const newFile = new File([result], file.name, {
          type: result.type,
          lastModified: Date.now(),
        });
        resolve(newFile);
      },
      error(err) {
        console.error("图片压缩失败:", err);
        Message.error("图片压缩失败，请重试");
        reject(false);
      },
    });
  });
};

// 图片上传成功处理
const handleUploadSuccess = (res: any) => {
  bannerForm.img = res.response.data.uuid;
};

// 组件挂载时初始化数据
onMounted(() => {
  fetchNotices();
  fetchBanners();
  fetchCategories();
});
</script>

<template>
  <div class="config-page">
    <!-- 模式切换选项卡 -->
    <a-card class="mode-card">
      <a-tabs v-model:active-key="activeMode">
        <a-tab-pane key="notice" title="通知配置">
          <a-card class="table-card">
            <div class="operation-wrapper">
              <a-button
                type="primary"
                @click="openNoticeModal('新增')"
                v-if="notices.length === 0"
              >
                <template #icon>
                  <icon-plus />
                </template>
                添加通知
              </a-button>
            </div>
            <a-table
              :columns="noticeColumns"
              :data="notices"
              :loading="noticeLoading"
              row-key="id"
              :pagination="false"
            />
          </a-card>
        </a-tab-pane>

        <a-tab-pane key="banner" title="首图配置">
          <a-card class="table-card">
            <div class="operation-wrapper">
              <a-button
                type="primary"
                @click="openBannerModal('新增')"
                v-if="banners.length < 3"
              >
                <template #icon>
                  <icon-plus />
                </template>
                添加首图
              </a-button>
            </div>
            <a-table
              :columns="bannerColumns"
              :data="banners"
              :loading="bannerLoading"
              row-key="id"
              :pagination="false"
            />
          </a-card>
        </a-tab-pane>
      </a-tabs>
    </a-card>

    <!-- 通知模态框 -->
    <a-modal
      v-model:visible="noticeModalVisible"
      :title="noticeModalTitle + '通知'"
      @ok="handleNoticeModalOk"
      @cancel="handleNoticeModalCancel"
    >
      <a-form :model="noticeForm" :rules="noticeRules" ref="noticeFormRef">
        <a-form-item label="通知标题" field="title">
          <a-input
            v-model:model-value="noticeForm.title"
            placeholder="请输入通知标题"
          />
        </a-form-item>
        <a-form-item label="通知内容" field="content">
          <a-textarea
            v-model:model-value="noticeForm.content"
            placeholder="请输入通知内容"
            allow-clear
          />
        </a-form-item>
      </a-form>
    </a-modal>

    <!-- 首图模态框 -->
    <a-modal
      v-model:visible="bannerModalVisible"
      :title="bannerModalTitle + '首图'"
      @ok="handleBannerModalOk"
      @cancel="handleBannerModalCancel"
    >
      <a-form :model="bannerForm" :rules="bannerRules" ref="bannerFormRef">
        <a-form-item label="首图标题" field="title">
          <a-input
            v-model:model-value="bannerForm.title"
            placeholder="请输入首图标题"
          />
        </a-form-item>
        <a-form-item label="排序" field="sort">
          <a-input-number
            v-model:model-value="bannerForm.sort"
            placeholder="请输入排序值"
            :min="0"
          />
        </a-form-item>
        <a-form-item label="首图" field="img">
          <a-upload
            action="/api/file/upload"
            :headers="{ Authorization: userCredit.token }"
            :file-list="bannerFileList"
            :limit="1"
            @success="handleUploadSuccess"
            :on-before-upload="onBeforeUpload"
          >
            <template #upload-button>
              <div class="upload-button">
                <div>
                  拖入或
                  <span style="color: #3370ff">点击选择图片上传</span>
                </div>
              </div>
            </template>
          </a-upload>
        </a-form-item>
        <a-form-item label="关联货品" field="goodId">
          <div style="display: flex; align-items: center">
            <a-button type="primary" @click="openGoodSelectModal">
              <template #icon>
                <icon-search />
              </template>
              选择货品
            </a-button>
            <div v-if="bannerForm.goodName" style="margin-left: 12px">
              已选择: {{ bannerForm.goodName }}
            </div>
          </div>
        </a-form-item>
      </a-form>
    </a-modal>

    <!-- 货品选择模态框 -->
    <a-modal
      v-model:visible="goodSelectModalVisible"
      title="选择关联货品"
      @cancel="goodSelectModalVisible = false"
      :footer="false"
      width="800px"
    >
      <a-form :model="goodSearchFilters" layout="inline">
        <a-form-item label="货品名称">
          <a-input
            v-model="goodSearchFilters.name"
            placeholder="请输入货品名称"
            style="width: 200px"
            allow-clear
          />
        </a-form-item>
        <a-form-item label="货品类别">
          <a-select
            v-model="goodSearchFilters.type"
            placeholder="请选择货品类别"
            allow-clear
            style="width: 200px"
          >
            <a-option v-for="cat in categories" :key="cat.id" :value="cat.name">
              {{ cat.name }}
            </a-option>
          </a-select>
        </a-form-item>
        <a-form-item>
          <a-button type="primary" @click="searchGoodsList">搜索</a-button>
        </a-form-item>
      </a-form>

      <a-table
        :columns="[
          { title: '名称', dataIndex: 'name' },
          { title: '类别', dataIndex: 'type' },
          { title: '价格（元）', dataIndex: 'price' },
          { 
            title: '操作', 
            width: 100,
            render: (row:any) => {
              return h(Button, {
                type: 'primary',
                onClick: () => selectGood(row.record),
              }, () => '选择');
            }
          }
        ]"
        :data="searchGoods"
        :loading="goodSearchLoading"
        row-key="id"
        :pagination="false"
        style="margin-top: 16px"
      />
    </a-modal>
  </div>
</template>

<style scoped lang="less">
.config-page {
  .mode-card {
    margin-bottom: 16px;
  }

  .table-card {
    margin-top: 16px;
  }

  .operation-wrapper {
    margin-bottom: 16px;
  }

  .upload-button {
    background-color: var(--color-fill-2);
    color: var(--color-text-1);
    border: 1px dashed var(--color-fill-4);
    height: 120px;
    width: 380px;
    border-radius: 2px;
    line-height: 120px;
    text-align: center;
  }
}
</style>
